package rpc

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"io"
	"log"
	"os"
	"tapd_c/proto"
	"time"
)

func Init() (proto.ExportClient, *grpc.ClientConn) {
	// 连接到server端，此处禁用安全传输
	conn, err := grpc.Dial("127.0.0.1:8972", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	//defer conn.Close()
	//创建客户端
	c := proto.NewExportClient(conn)
	// 执行RPC调用并打印收到的响应数据
	//调用服务端
	return c, conn
}

// RunServerFuc 一个调用server端方法的方法
func RunServerFuc(c proto.ExportClient, begin, end, lastBegin, lastEnd, fileName string) {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()
	// 开始调用server端的方法
	stream, err := c.ExportTap(ctx, &proto.ExportRequest{
		Begin:     begin,
		End:       end,
		LastBegin: lastBegin,
		LastEnd:   lastEnd,
		FileName:  fileName,
	})
	if err != nil {
		fmt.Printf("c.ExportTap failed:%v\n", err)
	}
	file, err := os.OpenFile(fmt.Sprintf("./doc/%s.xlsx", fileName), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println("open file failed, err:", err)
		return
	}
	defer file.Close()
	for {
		// 接收服务端返回的流式数据，当收到io.EOF或错误时退出
		res, err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatalf("c.LotsOfReplies failed, err: %v", err)
		}
		//将接收的写入到新的文档
		file.Write(res.One) //写入字节切片数据
	}
}
